package com.thoughtworks.android.androsphere.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import com.google.android.c2dm.C2DMessaging;
import com.thoughtworks.android.androsphere.R;

public class MainMenuActivity extends Activity {
    private static final String TAG = MainMenuActivity.class.getName();

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.menu);
        getWindow().setLayout(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        final Button register = (Button) findViewById(R.id.register);
        final Button deRegister = (Button) findViewById(R.id.deregister);
        final Button compose = (Button) findViewById(R.id.compose);

        String registrationId = C2DMessaging.getRegistrationId(this);

        if (registrationId != null && !"".equals(registrationId)) {
            enableMessaging(register, deRegister, compose);
        } else {
            disableMessaging(register, deRegister, compose);
        }
        bindActions(register, deRegister, compose);
    }

    private void bindActions(final Button register, final Button deRegister, final Button compose) {
        register.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                registerForCloudMessaging();
                enableMessaging(register, deRegister, compose);
            }
        });

        deRegister.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                deregisterFromCloudMessaging();
                disableMessaging(register, deRegister, compose);
            }
        });

        compose.setOnClickListener(new View.OnClickListener() {
            public void onClick(View view) {
                startActivityForResult(new Intent(view.getContext(), ComposeMessageActivity.class),0);
            }
        });
    }

    private void disableMessaging(Button register, Button deRegister, Button compose) {
        register.setEnabled(true);
        deRegister.setEnabled(false);
        compose.setEnabled(false);
    }

    private void enableMessaging(Button register, Button deRegister, Button compose) {
        register.setEnabled(false);
        deRegister.setEnabled(true);
        compose.setEnabled(true);
    }

    private void registerForCloudMessaging() {
        C2DMessaging.register(this, getResources().getString(R.string.sender_id));
        Log.d(TAG, "Sent registration request..");
    }

    private void deregisterFromCloudMessaging() {
        C2DMessaging.unregister(this);
        Log.d(TAG, "Sent de-registration request..");
    }
}
